/**
 * 
 */
package com.google.gwt.sample.stockwatcher.server;

import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.digester.rss.Channel;
import org.apache.commons.digester.rss.Item;
import org.apache.commons.digester.rss.RSSDigester;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.google.gwt.sample.stockwatcher.client.StockPrice;
import com.google.gwt.sample.stockwatcher.client.StockPriceService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * @author Prashanth
 *
 */
public class StockPriceServiceImpl extends RemoteServiceServlet implements StockPriceService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	 

	@Override
	public StockPrice[] getPrices(String[] symbols) {
		//Random rnd = new Random();
		System.out.println("inside RPC");
		StockPrice[] prices = new StockPrice[symbols.length];
	    for (int i=0; i<symbols.length; i++) {
	     // double price = rnd.nextDouble() * MAX_PRICE;
	      //double change = price * MAX_PRICE_CHANGE * (rnd.nextDouble() * 2f - 1f);

	    //  prices[i] = new StockPrice(symbols[i], price, change);
	    	try {
				prices[i] = fetchRSSFeeds(symbols[i]);
				System.out.println(prices[i].getPrice());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    return prices;
	}
	
	 public static StockPrice fetchRSSFeeds(String symbol) throws Exception {
	        RSSDigester digester=new RSSDigester();
	        
	        StringBuilder htmlToText = new StringBuilder();
	        String baseUrl = "http://www.nasdaq.com/aspxcontent/NasdaqRSS.aspx?data=quotes&symbol=";
	        String feed = baseUrl + symbol;
	        URL url=new URL(feed);
	        HttpURLConnection httpSource=
	            (HttpURLConnection)url.openConnection();
	        Channel channel=
	            (Channel)digester.parse(httpSource.getInputStream());
	        if (channel==null) {
	            throw new Exception("can't communicate with " + url);
	        }

	        Item rssItems[]=channel.findItems();
	        for (int i=0;i<rssItems.length;i++) {
	          // System.out.println(rssItems[i].getTitle());
	           //System.out.println(rssItems[i].getLink());
	           htmlToText.append(rssItems[i].getDescription());	           
	        }
	        
	        //call the html parser
	        StockPrice stockPriceFeed = parseStockFeedHtml(htmlToText.toString());
	        return stockPriceFeed;
	        
	        /*
	              to parse from a file instead of a URL
	        
	              import java.io.FileInputStream;
	              ...
	              String feed = "feed.xml"
	              FileInputStream fis = new FileInputStream(feed);
	              Channel channel=(Channel)digester.parse(fis);
	              ...
	       */
	    }

	@Override
	public StockPrice getPrice(String symbol) {
		StockPrice price = null;
		try {
	    	price = fetchRSSFeeds(symbol);  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return price;
	}
	
	private static StockPrice parseStockFeedHtml(String stockFeedHtml){
		StockPrice stockFetched = new StockPrice();
		try {

			Parser parser = new Parser();
			parser.setInputHTML(stockFeedHtml);
			parser.setEncoding("UTF-8");
			NodeList nl = parser.parse(null);
			NodeList trs = nl.extractAllNodesThatMatch(new TagNameFilter("tr"),
					true);
			StringBuilder strBuilder = new StringBuilder();
			for (int i = 0; i < trs.size(); i++) {
				NodeList nodes = trs.elementAt(i).getChildren();
				NodeList tds = nodes.extractAllNodesThatMatch(
						new TagNameFilter("td"), true);

				// Do stuff with tds
				strBuilder.append(tds.asString().trim());
			}

			String[] stringArray = strBuilder.toString().trim().split("&nbsp;");
			System.out.println(strBuilder.toString());
			String symbol = stringArray[0];
			String[] priceArray = stringArray[2].split(" ");
			String[] changeArray = stringArray[3].split(" ");
			String[] perChangeArray = stringArray[5].split(" ");
			String[] dateArray = stringArray[9].split(":");

			String perChange = perChangeArray[2].trim();
			String date = dateArray[1].trim();
			String price = priceArray[1].trim();
			String change = changeArray[1].trim();
			System.out.println("change: "+change);
			stockFetched.setChange(Double.parseDouble(change));
			stockFetched.setPrice(Double.parseDouble(price));
			stockFetched.setSymbol(symbol);			

		} catch (ParserException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
		return stockFetched;
	}
}
